import LogFile from "./LogFile";

var crypto = require("crypto");
/*==================================
公用函数对象
=====================================*/
export default class GlobDef {
    public constructor() {

    }

    public static VERSION_VAL: string = "0.1.0";

    public static s_preTime: number = -500;
    public static s_Date: Date = new Date();
    public static GetDate(): Date {
        if (Date.now() - GlobDef.s_preTime >= 500) {
            GlobDef.s_preTime = Date.now();
            GlobDef.s_Date = new Date();
        }
        return GlobDef.s_Date;
    }

    public static MD5Packet(str:string){
        return crypto.createHash('md5').update(String(str)).digest('hex');
    }

    public static GetTimeSec(): number {
        return Math.floor(GlobDef.GetDate().getTime() / 1000);
    }

    public static GetTickCnt():number{
        return GlobDef.GetDate().getTime();
    }
    
    public static SplitCfgString(str: string, spl: string): string[] {
        if (str == undefined)
            str = "";
        let vRtl = str.split(spl);
        return vRtl;
    }

    public static SplitCfgNum(str: string, spl: string): number[] {
        let vStr = str.split(spl);
        let vRtl: number[] = [];
        for (let i = 0; i < vStr.length; i++) {
            vRtl.push(parseInt(vStr[i]));
        }
        return vRtl;
    }


    public static CloneObj(obj: any) {
        let str, newobj = obj.constructor === Array ? [] : {};
        if (typeof obj !== 'object') {
            return;
        } else if (JSON) {
            str = JSON.stringify(obj), //序列化对象
                newobj = JSON.parse(str); //还原
        } else {
            for (let i in obj) {
                newobj[i] = typeof obj[i] === 'object' ? this.CloneObj(obj[i]) : obj[i];
            }
        }
        return newobj;
    }
    public static OutError(str:string){
        // cc.log(str); //生成环境自动消失
        console.error(str);

        LogFile.getInstance().OutError(str);
        // if(str == "error"){
        //     //@ts-ignore
        //     debugger;
        // }
    }
    public static OutPut(str:string){
        // cc.log(str); //生成环境自动消失
        console.log(str);

        LogFile.getInstance().OutLog(str);
        // if(str == "error"){
        //     //@ts-ignore
        //     debugger;
        // }
    }

    public static GetCov(x: number, y: number): number {
        if (Math.abs(x) + Math.abs(y) < 0.01)
            return 0;

        var roi: number = Math.atan2(x, y) * 180 / Math.PI;
        return roi;
    }

    public static GetDis(x: number, y: number): number {
        var fLen2 = x * x + y * y;
        return Math.sqrt(fLen2);
    }



    public static GetRandom(min: number, max: number) {
        return Math.floor(Math.random() * (max - min) + 0.5) + min;
    }

    //排序 order：false 从大到小 order: true 从小到大
    public static Sort(arr: Array<number>, order: boolean) {
        let compare = function (x: number, y: number) {
            if (x < y) {
                if (order) {
                    return -1;
                }
                return 1;
            } else if (x > y) {
                if (order) {
                    return 1;
                }
                return -1;
            } else {
                return 0;
            }
        };

        arr.sort(compare);
    }


    public static SplitToNums(str: string, split: string): number[] {
        let vRtl: number[] = [];
        let vStr = str.split(split);
        for (let i = 0; i < vStr.length; i++) {
            if(vStr[i].length == 0)
                vRtl.push(0);
            else
                vRtl.push(parseInt(vStr[i]));
        }
        return vRtl;
    }

    //是否为数字 包括字符串数字
    public static IsNumber(val: any): boolean {
        let regPos = /^\d+(\.\d+)?$/; //非负浮点数
        let regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
        if (regPos.test(val) || regNeg.test(val)) {
            return true;
        } else {
            return false;
        }
    }
    public static dateFormat(date?: any, format?: string): string {
        //无参数（0参）
        if (date == undefined && format == undefined) {
            date = new Date();
            format = "yyyy-MM-dd HH:mm:ss";
        }
        // //传入时间戳和格式（2参）
        // else if (typeof (time) != 'object' && !!format) {
        //     let bit=time.length<13?10**(13-time.length):1;
        //     let a=time+String(bit).substr(1)
        //     date = new Date(Number(a));
        // }
        //若只传入格式（1参）
        else if(typeof (date) == "string" && format == undefined){
            format = date;
            date = new Date();
        }
        //无格式化参数（1参）
        else if (format === undefined) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        //传入Date 和 格式（2参）
        else { }
        //没有分隔符的特殊处理

        var map = {
            "y": date.getFullYear() + "",//年份
            "M": date.getMonth() + 1 + "", //月份 
            "d": date.getDate() + "", //日 
            "H": date.getHours(), //小时 24
            "m": date.getMinutes() + "", //分 
            "s": date.getSeconds() + "", //秒 
            "q": Math.floor((date.getMonth() + 3) / 3) + "", //季度 
            "f": date.getMilliseconds() + "" //毫秒 
        };
        //小时 12
        if (map["H"] > 12) { map["h"] = map["H"] - 12 + ""; }
        else { map["h"] = map["H"] + ""; }
        map["H"] += "";

        var reg = "yMdHhmsqf";
        var all = "", str = "";
        for (var i = 0, n = 0; i < reg.length; i++) {
            n = format.indexOf(reg[i]);
            if (n < 0) { continue; }
            all = "";
            for (; n < format.length; n++) {
                if (format[n] != reg[i]) {
                    break;
                }
                all += reg[i];
            }
            if (all.length > 0) {
                if (all.length == map[reg[i]].length) {
                    str = map[reg[i]];
                }
                else if (all.length > map[reg[i]].length) {
                    if (reg[i] == "f") {
                        str = map[reg[i]] + this.charString("0", all.length - map[reg[i]].length);
                    }
                    else {
                        str = this.charString("0", all.length - map[reg[i]].length) + map[reg[i]];
                    }
                }
                else {
                    switch (reg[i]) {
                        case "y": str = map[reg[i]].substr(map[reg[i]].length - all.length); break;
                        case "f": str = map[reg[i]].substr(0, all.length); break;
                        default: str = map[reg[i]]; break;
                    }
                }
                format = format.replace(all, str);
            }
        }
        return format;
    }

     /**
    * 返回字符串 为n个char构成
    * @param char 重复的字符
    * @param count 次数
    * @return String
    * @author adswads@gmail.com
    */
      public static charString(char: string, count: number): string {
        var str: string = "";
        while (count--) {
            str += char;
        }
        return str;
    }

}